/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.Index;

import Models.Account;
import Models.DAOs.Account_DAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
/**
 * The log action of the system. 
 * @author Christian Magdaong
 */
public class login_action extends HttpServlet {

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            HttpSession session = request.getSession(true);
            int nloginCount;
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            nloginCount = (Integer)session.getAttribute("nloginCount");
            long creationTime, lastAccessTime, timeInterval;

            if(nloginCount < 3){

                Account newAccount = new Account_DAO().getAccount(username, password);
                if(newAccount != null){
                        String url = this.logInSuccess(session, newAccount);
                        response.sendRedirect(url);                      
                }
                else{
                        creationTime = session.getCreationTime();
                        lastAccessTime = session.getLastAccessedTime();
                        timeInterval = lastAccessTime - creationTime;
                        if(timeInterval > 1000)
                        {   
                            nloginCount+=1;
                            session.setAttribute("nloginCount", nloginCount);                   
                        }
                        response.sendRedirect("login");
                }             
            }

            if(nloginCount >= 3){              

                String remoteAddr = request.getRemoteAddr();
                ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
                reCaptcha.setPrivateKey("6LfdCc4SAAAAAI4p64kJ91fJl4NHEFMULd1ZP4QS");

                String challenge = request.getParameter("recaptcha_challenge_field");
                String uresponse = request.getParameter("recaptcha_response_field");
                ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

                if(reCaptchaResponse.isValid()){
                    Account newAccount = new Account_DAO().getAccount(username, password);
                    if(newAccount !=null){
                        session.invalidate();
                        HttpSession session1 = request.getSession(true);
                        String url = this.logInSuccess(session1, newAccount);
                        response.sendRedirect(url);
                    }
                    else{
                        creationTime = session.getCreationTime();
                        lastAccessTime = session.getLastAccessedTime();
                        timeInterval = lastAccessTime - creationTime;
                        if(timeInterval > 1000){   
                            nloginCount+=1;
                            session.setAttribute("nloginCount", nloginCount);                   
                        }
                        response.sendRedirect("login");                  
                    }                    
                }
                else{
                    response.sendRedirect("login");
                }                
            }
       
        } finally { 
            
            out.close();
        }
    }
     private String logInSuccess(HttpSession session,Account newAccount){
    
        String url = null;
        session.setAttribute("userID", newAccount.getUserID());
        session.setAttribute("userType", newAccount.getUserType());
        session.setAttribute("nloginCount",0);
        session.setAttribute("loggedin", true);
        switch(Integer.parseInt(newAccount.getUserType()))
        {
            case 0:
                url = "foobar_shop";
                break;
            case 1:
                url = "account_manager";
                break;
            case 2:
                url = "audio_manager";
                break;
            case 3:
                url = "book_manager";
                break;
            case 4:
               url = "dvd_manager";
                break;
            case 5:
                url = "magazine_manager";
                break;
            case 6:
                url  = "admin_home";
                break;                                                             
        }
        return url;
    
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
